﻿using DG.Tweening;
using QFramework;
using System.Linq;
using UnityEngine;

namespace ProjectIndieFarm
{
    public class ToolHand : ITool, IController
    {
        public string Name => "hand";

        public int Range => Global.PlantActionRange;

        public float TimeCost => Global.ToolHourCostHand;
        //TODO: 优化效率
        public float ActionDuration => 0.5f * (Global.ToolHourCostHand / Config.INIT_TOOL_HOUR_COST_HAND);

        public bool Selectable(ToolData data)
        {
            return Global.CurrentTool.Value.Name.Equals(Name)
                        && data.SoilGrid[data.CellPosition.x, 
                            data.CellPosition.y] != null
                        && data.SoilGrid[data.CellPosition.x,
                            data.CellPosition.y].HasPlant == true
                        && data.SoilGrid[data.CellPosition.x, 
                            data.CellPosition.y].PlantState == PlantStates.Ripe;
        }

        public void Use(ToolData toolData)
        {
            //
            if (PlantController.Instance.PlantGrid[toolData.CellPosition.x, toolData.CellPosition.y] as Plant)
            {
                var plant = PlantController.Instance.PlantGrid[toolData.CellPosition.x, toolData.CellPosition.y] as Plant;
                var icon = ResController.Instance.LoadSprite(Config.ItemForName[$"item_{plant.Name}"].IconName);
                var ripeCount = plant.SoilData.RipeCount;

                if (!this.SendCommand(new AddItemCountCommand($"item_{plant.Name}", ripeCount)))
                {
                    UIMessageQueue.Push("工具栏已满");
                    return;
                }
                UIMessageQueue.Push(icon, " 收获 ", true, ripeCount);

                //发送收获事件
                Global.OnPlantHarvest.Trigger(PlantController.Instance.PlantGrid[toolData.CellPosition.x, toolData.CellPosition.y]);

                //收获动画
                var collectionIconTemplate = UIToolbar.Instance.CollectionIconTemplate;
                var plantScreenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, toolData.WorldPosition);

                if (RectTransformUtility.ScreenPointToLocalPointInRectangle(UIToolbar.Instance.transform as RectTransform, plantScreenPoint, null, out var plantPosInToolbar))
                {
                    for (int i = 0; i < ripeCount; i++)
                    {
                        collectionIconTemplate.InstantiateWithParent(UIToolbar.Instance.transform)
                            .LocalPosition(plantPosInToolbar)
                            .Show()
                            .Self(self =>
                            {
                                //TODO:现在是飞入道具栏，后续改成飞入背包
                                var targetPos = UIToolbar.Instance.ToolbarSlots.FirstOrDefault(slot => slot.Data != null && slot.Data.ItemID.Value == $"item_{plant.Name}");
                                self.sprite = icon;
                                self.transform.localScale = Vector3.one * Random.Range(0.2f, 0.8f);
                                self.transform.DOScale(Vector3.one, 0.5f);
                                DOTween.Sequence()
                                    .Append(self.transform.DOMove(self.transform.position + new Vector3(Random.Range(-0.5f, 0.5f), 1, 0).normalized * 128f, 0.3f)
                                    .SetEase(Ease.OutCubic))
                                    .Append(self.transform.DOMove(targetPos.transform.position, 0.2f)
                                    .SetEase(Ease.InCubic)
                                    .OnComplete(() => { self.DestroyGameObj(); }));
                            });
                    }
                }
            }


            //摘取果实
            Object.Destroy(PlantController.Instance.PlantGrid[toolData.CellPosition.x, toolData.CellPosition.y].GameObject);
            PlantController.Instance.PlantGrid[toolData.CellPosition.x, toolData.CellPosition.y] = null;
            toolData.SoilGrid[toolData.CellPosition.x, toolData.CellPosition.y] = null;
            var gridController = Object.FindObjectOfType<GridController>();
            gridController.Water.SetTile(new Vector3Int(toolData.CellPosition.x, toolData.CellPosition.y), null);



            AudioController.Instance.SfxHarvest.Play();

            CameraController.ShakeMiddle();
        }

        public IArchitecture GetArchitecture()
        {
            return Global.Interface;
        }
    }
}
